package com.zhaoyh.controller;

import com.alibaba.fastjson.JSON;
import com.zhaoyh.bean.IncomeRecord;
import com.zhaoyh.framework.code.model.PageBean;
import com.zhaoyh.result.ChartsIncomeResule;
import com.zhaoyh.service.IncomeRecordService;
import com.zhaoyh.util.MathUtils;
import com.zhaoyh.vo.IncomeChartsVO;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author 祥霸
 * @date 2019/2/12
 */
@Controller
@RequestMapping(value = "/income")
public class IncomeRecordController {

    @Autowired
    IncomeRecordService incomeRecordService;

    /**
     * 分页查询：返回指定页数对应的数据
     * @param pageNo
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ModelAndView getDeptList(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo){
        ModelAndView mv = new ModelAndView("incomePage");
        //每页显示的记录行数
        int limit = 200;
        //总记录数
        int totalItems = incomeRecordService.getCount();
        int temp = totalItems / limit;
        int totalPages = (totalItems % limit== 0) ? temp : temp+1;
        //每页的起始行(offset+1)数据，如第一页(offset=0，从第1(offset+1)行数据开始)
        int offset = (pageNo - 1)*limit;
        List<IncomeRecord> departments = incomeRecordService.listIncomeRecord(offset, limit);

        mv.addObject("departments", departments)
                .addObject("totalItems", totalItems)
                .addObject("totalPages", totalPages)
                .addObject("curPageNo", pageNo);
        return mv;
    }

    @RequestMapping("listMain")
    public ModelAndView getList(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber) {
        ModelAndView mv = new ModelAndView("console/listIncome");

        try {
            //每页显示的记录行数
            int limit = 200;
            //总记录数
            PageBean pageBean = new PageBean(limit);

            int totalItems = incomeRecordService.getCount();
            if (limit * pageNumber > totalItems) {
                pageNumber = MathUtils.ceil(totalItems, limit);
            }
            pageBean.setDataSum(totalItems);
            pageBean.setPageNumber(pageNumber);
            //每页的起始行(offset+1)数据，如第一页(offset=0，从第1(offset+1)行数据开始)
            int offset = (pageNumber - 1)*limit;
            List<IncomeRecord> departments = incomeRecordService.listIncomeRecord(offset, limit);

            mv.addObject("departments", departments)
                    .addObject("pageBean", pageBean);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return mv;
    }

    @RequestMapping(value = "/ajaxChartsList", method = RequestMethod.POST)
    public void getChartsList(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo, HttpServletResponse response) {
        //每页显示的记录行数
        int limit = 20000;
        //总记录数
        int totalItems = incomeRecordService.getCount();
        int temp = totalItems / limit;
        int totalPages = (totalItems % limit== 0) ? temp : temp+1;
        //每页的起始行(offset+1)数据，如第一页(offset=0，从第1(offset+1)行数据开始)
        int offset = (pageNo - 1)*limit;
        List<IncomeRecord> departments = incomeRecordService.listIncomeRecord(offset, limit);

        ChartsIncomeResule resule = new ChartsIncomeResule();

        double maxIncome = 0.0;

        if (departments != null) {
            for (IncomeRecord income: departments) {
                IncomeChartsVO incomeChartsVO = new IncomeChartsVO();
                incomeChartsVO.setDate(income.getDataTime());
                incomeChartsVO.setValue(income.getMoney());
                incomeChartsVO.setFullDate(DateFormatUtils.format(income.getDataTime(), "yyyy-MM-dd HH:mm:ss"));

                double money = income.getMoney();

                resule.getList().add(incomeChartsVO);
                resule.getDouList().add(money);

                if (maxIncome < Math.abs(money)) {
                    maxIncome = Math.abs(money);
                }
            }
        }

        resule.getDouList().add(maxIncome + 1);

        String jsonResult = JSON.toJSONString(resule);
        renderData(response, jsonResult);
    }

    /**
     * 通过PrintWriter将响应数据写入response，ajax可以接受到这个数据
     *
     * @param response
     * @param data
     */
    private void renderData(HttpServletResponse response, String data) {
        PrintWriter printWriter = null;
        try {
            printWriter = response.getWriter();
            printWriter.print(data);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (null != printWriter) {
                printWriter.flush();
                printWriter.close();
            }
        }
    }
}
